//
//  YDContactsManager.m
//  IngCard
//
//  Created by kf on 2017/5/17.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDContactsManager.h"
#import "YDHttpClient.h"
#import "YDAPI.h"
#import "YDAccountManager.h"


/*! 索引 */
#define kLocalizedIndexArrayKey @"kLocalizedIndexArrayKey"
/*! 排序后的分组，可以为 model */
#define kLocalizedGroupArrayKey @"kLocalizedGroupArrayKey"


@interface YDContactsManager ()
@end

@implementation YDContactsManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static YDContactsManager *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
        instance.sortType = (YDContactSort)([[NSUserDefaults standardUserDefaults] valueForKey:@"Contact_sortType"]);
    });
    return instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone{
    return [self sharedInstance];
}


-(void) getListOnComplete:(void (^)(BOOL success, NSString* msg)) onComplete
{
    [HTTP POST:API.contact_list parameters:^(NSMutableDictionary *parameters) {
        [parameters safeSetObject:ACCOUNT.account.uid forKey:@"uid"];
        [parameters safeSetObject:ACCOUNT.account.login_token forKey:@"login_token"];
    } onComplete:^(BOOL success, NSDictionary *response, NSString *msg) {
        NSArray *listArray = NSArrayMake(response[@"list"]);
        
        self.contacts = [YDContact serializeWithListJson:listArray];
        BlockGoGo(onComplete,success,msg);
    }];
}


-(void) add:(NSArray<NSString *> *) uids
 OnComplete:(void (^)(BOOL success, NSString* msg)) onComplete
{
    if ((!uids) || (uids.count == 0)) return;
    
    [HTTP POST:API.contact_add parameters:^(NSMutableDictionary *parameters) {
        [parameters safeSetObject:[uids componentsJoinedByString:@","] forKey:@"c_uid"];
        [parameters safeSetObject:ACCOUNT.account.uid forKey:@"uid"];
        [parameters safeSetObject:ACCOUNT.account.login_token forKey:@"login_token"];
    } onComplete:^(BOOL success, NSDictionary *response, NSString *msg) {
        BlockGoGo(onComplete,success,msg);
    }];
}

 
-(void) del:(NSArray<NSString *> *) uids
 OnComplete:(void (^)(BOOL success, NSString* msg)) onComplete
{
    if ((!uids) || (uids.count == 0)) return;
    
    [HTTP POST:API.contact_del parameters:^(NSMutableDictionary *parameters) {
        [parameters safeSetObject:[uids componentsJoinedByString:@","] forKey:@"c_uid"];
        [parameters safeSetObject:ACCOUNT.account.uid forKey:@"uid"];
        [parameters safeSetObject:ACCOUNT.account.login_token forKey:@"login_token"];
    } onComplete:^(BOOL success, NSDictionary *response, NSString *msg) {
        
        BlockGoGo(onComplete,success,msg);
    }];
}

-(void) sort
{
    NSDictionary *dict = nil;
    switch (self.sortType) {
        case YDContactSort_name:
        case YDContactSort_none:
        {
            dict = [self localizedWithDataArray:self.contacts
                               localizedNameSEL:@selector(username)];
        }
            break;
        case YDContactSort_company:
        {
            dict = [self localizedWithDataArray:self.contacts
                               localizedNameSEL:@selector(company)];
        }
            break;
        default:
            break;
    }
    
    if (dict)
    {
        self.indexArray_sort =  NSArrayMake(dict[kLocalizedIndexArrayKey]);
        self.contacts_sort = NSArrayMake(dict[kLocalizedGroupArrayKey]);
    }
}

#pragma mark - private
- (NSDictionary *)localizedWithDataArray:(NSArray *)dataArray
                        localizedNameSEL:(SEL)localizedNameSEL
{
    /*! 对数组重建索引，按照abcd字母顺序进行分组 */
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    NSInteger index, sectionTitlesCount = [[indexCollation sectionTitles] count];
    NSMutableArray *indexArray = [[NSMutableArray alloc] initWithArray:[indexCollation sectionTitles]];
    
    /*! 临时数据，存放 section 对应的 userObjc 数组数据 */
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    
    /*! 设置sections数组初始化：元素包含userObjs数据的空数据 */
    for (index = 0; index < sectionTitlesCount; index++)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    
    /*! 分组 */
    for (id object in dataArray)
    {
        /*! 根据timezone的localename，获得对应的的section number */
        NSInteger sectionNumber = [indexCollation sectionForObject:object collationStringSelector:localizedNameSEL];
        /*! 根据sectionNumber获取数组 */
        NSMutableArray *sectionUserObjs = [newSectionsArray objectAtIndex:sectionNumber];
        /*! 添加对象到对应的数组中 */
        [sectionUserObjs addObject:object];
    }
    
    /*! 获取空的数组的index */
    NSMutableArray *willDeleteAry = [NSMutableArray new];
    for (int i = 0; i < newSectionsArray.count; i ++)
    {
        NSArray *tempAry = newSectionsArray[i];
        if (tempAry.count == 0) {
            [willDeleteAry addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    
    /*! 删除空的数组 */
    for (NSInteger i = willDeleteAry.count; i > 0; i -- )
    {
        NSInteger index = [willDeleteAry[i - 1] integerValue];
        [newSectionsArray removeObjectAtIndex:index];
        [indexArray removeObjectAtIndex:index];
    }
    
    /*! 该字典中存放分组排序呢后的索引及数据 */
    NSDictionary *dict = @{kLocalizedGroupArrayKey : newSectionsArray,
                           kLocalizedIndexArrayKey : indexArray};
    
    return dict;
}


#pragma mark - lazy Loading

-(void) setSortType:(YDContactSort)sortType
{
    if (_sortType != sortType)
    {
        _sortType = sortType;
        [[NSUserDefaults standardUserDefaults] setValue:@(_sortType) forKey:@"Contact_sortType"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

@end


